public class Solution617 {
    /**
     * 给定两个二叉树，想象当你将它们中的一个覆盖到另一个上时，两个二叉树的一些节点便会重叠。
     * <p>
     * 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠，那么将他们的值相加作为节点合并后的新值，否则不为 NULL 的节点将直接作为新二叉树的节点。
     * <p>
     * 示例 1:
     * <p>
     * 输入:
     * Tree 1                       Tree 2
     * 1                         2
     * / \                       / \
     * 3   2                     1   3
     * /                           \   \
     * 5                             4   7
     * 输出:
     * 合并后的树:
     * 3
     * / \
     * 4   5
     * / \   \
     * 5   4   7
     */

    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null || t2 == null) {
            return t1 == null ? t2 : t1;
        }
        TreeNode res = new TreeNode(t1.val + t2.val);
        merge(t1, t2, res);
        return res;
    }

    public void merge(TreeNode t1, TreeNode t2, TreeNode res) {
        if (t1.left != null || t2.left != null) {
            if (t1.left == null){
                res.left = t2.left;
            }else if (t2.left == null){
                res.left = t1.left;
            }else {
                res.left = new TreeNode(t1.left.val + t2.left.val);
                merge(t1.left, t2.left, res.left);
            }
        }
        if (t1.right != null || t2.right != null) {
            if (t1.right == null){
                res.right = t2.right;
            }else if (t2.right == null){
                res.right = t1.right;
            }else {
                res.right = new TreeNode(t1.right.val + t2.right.val);
                merge(t1.right, t2.right, res.right);
            }
        }
    }


    public TreeNode mergeTrees2(TreeNode t1, TreeNode t2){
        if (t1 == null) return t2;
        if (t2 == null) return t1;
        t1.val += t2.val;
        t1.left = mergeTrees2(t1.left, t2.left);
        t1.right = mergeTrees2(t1.right, t2.right);
        return t1;
    }
}
